package com.quefly.game.xbdt2.android;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Filter;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ArrayMap;
import com.oahcfly.chgame.core.freefont.FreeFont;
import com.oahcfly.chgame.core.freefont.FreeListener;
import com.oahcfly.chgame.core.freefont.FreePaint;

public class AndroidFreeFont implements FreeListener {
	public static void Strat() {
		FreeFont.Start(new AndroidFreeFont());
	}

	private AndroidFreeFont() {
		if (paint == null) {
			paint = new Paint();
			paint.setAntiAlias(true);
		}
	}

	private Paint paint = null;

	private int getColor(Color color) {
		return ((int) (255 * color.a) << 24) | ((int) (255 * color.r) << 16) | ((int) (255 * color.g) << 8)
				| ((int) (255 * color.b));
	}

	public Pixmap getFontPixmap(String txt, FreePaint vpaint) {
		Pixmap.setFilter(Filter.BiLinear);
		if (paint == null) {
			paint = new Paint();
			paint.setAntiAlias(true);
		}
		paint.setTextSize(vpaint.getTextSize());
		FontMetrics fm = paint.getFontMetrics();
		int w = (int) paint.measureText(txt);
		int h = (int) (fm.descent - fm.ascent);
		if (w == 0) {
			w = h = vpaint.getTextSize();
		}
		Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
		Canvas canvas = new Canvas(bitmap);
		// 如果是描边类型
		if (vpaint.getStrokeColor() != null) {
			// 绘制外层
			paint.setColor(getColor(vpaint.getStrokeColor()));
			paint.setStrokeWidth(vpaint.getStrokeWidth()); // 描边宽度
			paint.setStyle(Style.FILL_AND_STROKE); // 描边种类
			paint.setFakeBoldText(true); // 外层text采用粗体
			canvas.drawText(txt, 0, -fm.ascent, paint);
			paint.setFakeBoldText(false);
		} else {
			paint.setUnderlineText(vpaint.getUnderlineText());
			paint.setStrikeThruText(vpaint.getStrikeThruText());
			paint.setFakeBoldText(vpaint.getFakeBoldText());
		}
		// 绘制内层
		paint.setStrokeWidth(0);
		paint.setColor(getColor(vpaint.getColor()));
		canvas.drawText(txt, 0, -fm.ascent, paint);
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 70, buffer);
		byte[] encodedData = buffer.toByteArray();
		Pixmap pixmap = new Pixmap(encodedData, 0, encodedData.length);
		bitmap.recycle();
		bitmap = null;
		canvas = null;
		try {
			buffer.close();
		} catch (IOException e) {
			buffer = null;
		}
		return pixmap;
	}

	@Override
	public ArrayMap<String, Pixmap> getBatchFontPixmap(Array<String> arg0, FreePaint arg1) {
		// TODO Auto-generated method stub
		return null;
	}
}
